
#include "Core/EnemySpawner.h"

#include "Character/Character2D.h"
#include "Enemy/Enemy2D.h"
#include "Kismet/GameplayStatics.h"

AEnemySpawner::AEnemySpawner()
{
	PrimaryActorTick.bCanEverTick = true;

}

void AEnemySpawner::BeginPlay()
{
	Super::BeginPlay();
	if (!Player)
	{
		AActor* PlayerActor =  UGameplayStatics::GetActorOfClass(GetWorld(), ACharacter2D::StaticClass());
		if (PlayerActor)
		{
			Player = Cast<ACharacter2D>(PlayerActor);
		}
	}
	
	StartSpawning();
}

void AEnemySpawner::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	
}



void AEnemySpawner::StartSpawning()
{
	GetWorldTimerManager().SetTimer(SpawnTimer, this, &AEnemySpawner::OnSpawnTimerTimeout, SpawnTime, true, SpawnTime);
}

void AEnemySpawner::StopSpawning()
{
	GetWorldTimerManager().ClearTimer(SpawnTimer);
}

void AEnemySpawner::OnSpawnTimerTimeout()
{
	SpawnEnemy();
}

void AEnemySpawner::SpawnEnemy()
{
	// 生成敌人
	FVector RandomPosition = FMath::VRand();
	RandomPosition.Z = 0.0f;
	RandomPosition.Normalize();
	RandomPosition *= SpawnDistance;
	AEnemy2D* Enemy = GetWorld()->SpawnActor<AEnemy2D>(EnemyActorToSpawn, GetActorLocation() + FVector(RandomPosition.X, RandomPosition.Y, 0.0f), FRotator::ZeroRotator);
	SetupEnemy(Enemy);
	
	// Increase The Difficulty
	TotalEnemyCount ++;
	if (TotalEnemyCount % DifficultySpawnInterval == 0)
	{
		SpawnTime -= DecreaseSpawnTimeByEveryInterval;
		if (SpawnTime < SpawnTimeMinimumLimit)
		{
			SpawnTime = SpawnTimeMinimumLimit;
		}

		StopSpawning();
		StartSpawning();
	}
}

void AEnemySpawner::SetupEnemy(AEnemy2D* Enemy)
{
	if (Enemy)
	{
		Enemy->Player = Player;
		Enemy->CanFollow = true;
	}	
}

